package common.kingdee.controller;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import common.kingdee.cas.WebHookUtil;
import common.kingdee.domain.KingdeeUser;
import common.mybatis.plugin.enhancedCache.impl.MyBatisCacheManagerImpl;
import common.security.domain.repositoryInterface.DepartmentRepository;
import common.security.domain.repositoryInterface.UserRepository;

@RestController
public class ClearChacheEventHandler {
    @Value("${APPID}")
	private String appId;
    @Value("${SECRET}")
	private String secret;
    @Autowired
    private UserRepository<KingdeeUser> userRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
	@RequestMapping("/clearChache")
	public String clearChache(@RequestHeader Map<String, String> header, @RequestParam String eid,@RequestParam String eventType,
	@RequestParam String eventId,@RequestParam String createTime) {
		String contentBody = "eid=" + eid+ "&eventType=" + eventType + "&eventId=" + eventId+"&createTime="+createTime;
		Map<String,String> paramsMap = new TreeMap<String,String>();
		paramsMap.put("eid", eid);
		paramsMap.put("eventType", eventType);
		paramsMap.put("eventId", eventId);
		paramsMap.put("createTime", createTime);
		contentBody = mapToString(paramsMap);
		if(WebHookUtil.checkAuth(appId, secret, contentBody, header)){
			if(eventType.equals("dataUpdated")){
				departmentRepository.clearCache();
				userRepository.clearCache();
				MyBatisCacheManagerImpl.getInstance().clearAllCaches();
			}
		}else{
			System.out.println("接收到一个非法推送");
			return "not ok";
		}
		return "ok";
	}
	
	// 按key字段顺序排序，组装k1=v1&k2=v2形式
	private String mapToString(Map<String, String> map) {
	    StringBuilder sb = new StringBuilder();
	    Set<String> keys = map.keySet();
	    for (String key : keys) {
	        sb.append(key).append("=").append(map.get(key)).append("&");
	    }
	    if (sb.length() > 0) {
	        return sb.substring(0, sb.length() - 1);
	    } else {
	        return sb.toString();
	    }
	}

	public static void main(String[] args) {
		SpringApplication.run(ClearChacheEventHandler.class, args);
	}
}
